package com.tongguan.paypos.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.tongguan.paypos.R;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.PayInfo;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.entity.TransUnionInfo;
import com.tongguan.paypos.utils.AppUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;
import com.tongguan.paypos.view.CustomAlertDialog;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Joylive on 2016/12/17 .
 */

public class PrintRandomFragment extends BaseFragment{
    private static final int REQUEST_CODE_COUPON = 10070;
    private static final int PRINT_RANDOM = 10080;
    @BindView(R.id.btn_scan_bar)
    Button mBtnScanBar;
    @BindView(R.id.et_input_order)
    EditText mEtInputOrder;
    @BindView(R.id.radioBtn_online)
    RadioButton mRadioBtnOnline;
    @BindView(R.id.radioBtn_union)
    RadioButton mRadioBtnUnion;
    @BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;
    @BindView(R.id.btn_repeat)
    Button mBtnRepeat;

    private int genre = 0;//0 线上（默认） 1 线下
    public final static String REPEAT = "repeat";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        rootView = inflater.inflate(R.layout.fragment_print_repeat_random, container, false);
        setTitle("打印任意一笔");
        ButterKnife.bind(this, rootView);
        initEvent();
        return rootView;
    }

    private void initEvent(){
        mBtnScanBar.setOnClickListener(v -> startActivityForResult( new Intent(frmCtx, CaptureActivity.class), REQUEST_CODE_COUPON));
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if(checkedId == mRadioBtnOnline.getId()){
                mEtInputOrder.setHint(R.string.hint_order);
                mBtnScanBar.setVisibility(View.VISIBLE);
                genre = 0;
                mEtInputOrder.setText("");
            }else if(checkedId == mRadioBtnUnion.getId()){
                mEtInputOrder.setHint(R.string.hint_trans);
                mBtnScanBar.setVisibility(View.INVISIBLE);
                genre = 1;
                mEtInputOrder.setText("");
            }
        });
        mBtnRepeat.setOnClickListener(v -> {
            String number = mEtInputOrder.getText().toString();
            if(genre == 0){
                if(TextUtils.isEmpty(number)){
                    ToastUtils.showCustom(frmCtx, "输入内容为空！");
                    return;
                }
                queryOderDetail(number);
            }else{
                Bundle bundle = new Bundle();
                bundle.putInt("menuId", 14000);
                AppUtils.runComponent(frmCtx, AppConstants.UNION_PAY_APP_PACKAGE, AppConstants.PRINT_DIR, bundle, PRINT_RANDOM);
            }
        });
    }

    /**
     * 查询订单详情接口
     */
    private void queryOderDetail(String orderId){
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(frmCtx, UrlConstants.ORDER_DETAILS + orderId, params, mDialog, new AbstractRequestCallback(){
            @Override
            public void onResponse(String response, int id){
                PayInfo payInfo = PayInfo.objectFromData(response);
                if(payInfo.getStatus() != 100){
                    ToastUtils.showCustom(frmCtx, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if(transInfo == null){
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title).setMessage(payInfo.getMessage() + "\n订单详情查询失败，是否重新请求").setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail(orderId)).setNegativeButton(R.string.common_cancel, null).show();
                    return;
                }
                //成功跳转
                //                if (!"0".equals(transInfo.getState())){
                //                    ToastUtils.showCustom(frmCtx,"撤销或失败的订单不支持重打印");
                //                    return;
                //                }
                PrintDetailFragment fragment = new PrintDetailFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelable(PrintDetailFragment.PRINT_DETAIL, transInfo);
                bundle.putString(PrintDetailFragment.PRINT_REPEAT,REPEAT);
                fragment.setArguments(bundle);
                getFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
            }

            @Override
            public void onError(Call call, Exception e, int id){
                super.onError(call, e, id);
                new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.error_net).setMessage(e.getMessage()).setPositiveButton("重新加载", (dialog, which) -> queryOderDetail(orderId)).setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
        if(data != null){
            Bundle bundle = data.getExtras();
            if(bundle == null){
                return;
            }
            //线上支付
            if(requestCode == REQUEST_CODE_COUPON){
                if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtInputOrder.setText(result);
                }else if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED){
                    L.d("解析二维码失败");
                }
            }
            //银联
            if(requestCode == PRINT_RANDOM){
                if(resultCode == Activity.RESULT_OK){
                    TransUnionInfo info = Utils.assembleTransUnionInfo(bundle, "打印", true);
                    L.d("银联：" + info.toString());
                }else{
                    TransUnionInfo info = Utils.assembleTransUnionInfo(bundle, "打印", false);
                    L.d("银联：" + info.toString());
                    ToastUtils.showCustomLong(frmCtx, "暂无记录或已经结算");
                }
            }
        }
    }
}
